﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace TypedMvcActionHelper
{
    public static class TypedActionLinkGenerator
    {
        public static MvcHtmlString GenerateActionLink<TController>(this HtmlHelper htmlHelper, string linkText, Expression<Func<TController, ActionResult>> expression, object htmlAttributes)
            where TController : ControllerBase
        {

            var definition = MvcInvocationDefinition.Create(expression);

            return htmlHelper.ActionLink(linkText, definition.ActionName, definition.ControllerName, definition.RouteValues, ToDictionary(htmlAttributes));
        }

        private static IDictionary<string,object> ToDictionary(object htmlAttributes)
        {
            var dictionary=new Dictionary<string,object>();
            if (htmlAttributes != null)
            {
                foreach (var attribute in htmlAttributes.GetType().GetProperties())
                {
                    dictionary.Add(attribute.Name, attribute.GetValue(htmlAttributes));
                }
            }
            return dictionary;
        } 

    }
}